/**
 * 
 */
package com.base.myproject.client.busi.business;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.ccode.CcodeSelect;
import com.base.myproject.client.busi.storeslist.GcodeSelectDialog;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.CommandPrepareCall;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.ui.BaseBusiLeftPanel;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * @author zgw
 *2009-8-30 下午01:45:08
 * javazgw@gmail.com
 */
public class ShipOrder extends BaseJDBCPanel implements BusinessRatify,AsyncCallback<CommandSyncReturnObject>{
	
	 BaseStore<BusiObject> store = null;
	 BaseGrid<BusiObject> grid = null;
	 final static String busi = SystemMessage.busi[2];
	 Button addstorelistg = new Button("库存商品选择");
	
	 Html gcodetip= new Html();
	 BaseStore<BusiObject> shipordergcode ;
	 TextField<String> busistatus = new TextField<String>();
	 BaseComboBoxForm<BaseModelData> ccode;
	public ShipOrder() {
		super();
		init();
	}
	public void complete()
	{
		super.complete();
		ttiratify.setText("提交确认");
		getToolbarll().add(ttiratify);
	}
	public void init() {
		this.setWidth("920px");
		this.setAutoHeight(true);
		
		initlistener();
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
	    centerData.setMargins(new Margins(5, 5, 0, 0));  
	    this.add(initWeigetx(),centerData);
	    
	    registerMainStore(getStore());
		registerStore(getStore());
		
		this.setBusino(busi);
	    setdefault();
	    busistatus.setFireChangeEventOnSetValue(true);
	}
	public ContentPanel initWeigetx() {
		ContentPanel panel = new ContentPanel();
		panel.setHeaderVisible(false);
		panel.setLayout(new BorderLayout());
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, 250);
		westData.setSplit(true);
		westData.setCollapsible(true);
		westData.setMargins(new Margins(0));
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 0, 5, 0));
		panel.add(CreateLeftPanel(), westData);
		panel.add(CreateMain(), centerData);
		panel.setSize(940, 450);
		return panel;
	}

	private void setdefault()
	{
		getStore().addDefault("busicode", busi);
		getStore().addDefault("bcode", Env.getEnvbcode());
		getStore().addDefault("busistatus","1");
	}
	void initlistener()
	{
		
	}
	
	/**
	 * 合同管理左边查询
	 * @return
	 */
		public ContentPanel CreateLeftPanel() {
			List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
			ColumnConfig cname = new ColumnConfig("codename", "发货编号", 200);
			TextField<String> gnametext = new TextField<String>();

			columns.add(cname);
			DateField dateField = new DateField();

			ColumnModel cm = new ColumnModel(columns);

			// --set modetype
			ModelType type = new ModelType();
			type.setRoot("records");
			type.setRecordName("record");
			type.setTotalName("totle");
			type.addField("icode");
			type.addField("bcode");
			type.addField("ccode");
			type.addField("busistatus");
			type.addField("vprepare");
			type.addField("predate");
			type.addField("modifydate");
			type.addField("codename");
//			type.addField("outordercode");
//			type.addField("subscribedate");
			type.addField("odate");
			type.addField("mark");
			type.addField("shipper");
			type.addField("shipaddr");
			type.addField("shipzip");
			type.addField("shipphone");
			type.addField("receiver");
			type.addField("receiveddr");
			type.addField("receivezip");
			type.addField("receivephone");
			type.addField("gooddesc");
			// type.addField("Phone");
			// type.addField("imagepath");
			StoreInfo info = new StoreInfo();
			info.setTablename("shiporder");
			info.setSql("select * from shiporder where busicode ='"+busi+"'");
			info.setKeyname(new String[] { "icode","codename" });
			BaseBusiLeftPanel basbusileftpanel = new BaseBusiLeftPanel(columns,
					type, info);
			setStore(basbusileftpanel.getStore());
			//getStore().setKeyname(new String[] { "codename" });

			basbusileftpanel.getGrid().setAutoExpandColumn("codename");
			setMaincomponent(basbusileftpanel.getGrid());
			
			return basbusileftpanel.getPanel();
		}
		/**
		 * 主界面
		 * @return
		 */
		private ContentPanel CreateMain()
		{
			ContentPanel panel = new ContentPanel();
			panel.setWidth("400px");
			panel.setHeight("400px");
			panel.setHeaderVisible(false);
//			panel.setAutoHeight(true);
//			panel.setAutoWidth(true);
			BaseFormPanel leftpanel = new BaseFormPanel(getStore());
			leftpanel.setBodyBorder(false);
			leftpanel.setHeaderVisible(false);
			
			BaseFormPanel rightpanel = new BaseFormPanel(getStore());
			rightpanel.setBodyBorder(false);
			rightpanel.setHeaderVisible(false);
			
			//_________________________________
			TextField<String> codename = new TextField<String>();
			codename.setName("codename");
			codename.setAllowBlank(false);
			codename.setFieldLabel("发货单编码");

			
			TextField<String> bcode = new TextField<String>();
			bcode.setName("bcode");

			bcode.setFieldLabel("部门人员");
			CcodeSelect ccodeselect = new CcodeSelect(1);
			ccode = ccodeselect.getCcodeSelect();
			ccode.setName("ccode");
			
			ccode.setFieldLabel("客户");
			
			
			busistatus.setName("busistatus");
		//	busistatus.setEnabled(false);
			busistatus.setFieldLabel("状态");

			TextArea mark = new TextArea();
			mark.setName("mark");
			mark.setFieldLabel("备注");
			mark.setMaxLength(250);
			
			TextField<String> shipper = new TextField<String>();
			shipper.setName("shipper");
			shipper.setFieldLabel("发货人");

			TextField<String> shipaddr = new TextField<String>();
			shipaddr.setName("shipaddr");
			shipaddr.setFieldLabel("发货地址");

			TextField<String> shipzip = new TextField<String>();
			shipzip.setName("shipzip");
			shipzip.setFieldLabel("发货地邮编");

	

			TextField<String> shipphone = new TextField<String>();
			shipphone.setName("shipphone");
			shipphone.setFieldLabel("发货人电话");

			TextField<String> receiver = new TextField<String>();
			receiver.setName("receiver");
			receiver.setFieldLabel("收货人");

			TextField<String> receiveddr = new TextField<String>();
			receiveddr.setName("receiveddr");
			receiveddr.setFieldLabel("收货地址");

			TextField<String> receivezip = new TextField<String>();
			receivezip.setName("receivezip");
			receivezip.setFieldLabel("收货地邮编");
			
			TextField<String> receivephone = new TextField<String>();
			receivephone.setName("receivephone");
			receivephone.setFieldLabel("收货人电话");
			
			TextArea gooddesc = new TextArea();
			gooddesc.setName("gooddesc");
			gooddesc.setFieldLabel("货品描述");	
			gooddesc.setMaxLength(500);
			
			
			leftpanel.add(codename);
			leftpanel.add(bcode);
			leftpanel.add(shipper);
			leftpanel.add(shipaddr);
			leftpanel.add(shipzip);
			leftpanel.add(shipphone);
			leftpanel.add(gooddesc,new FormData(161, 46));
//			leftpanel.add(codename);
			
			
		
			rightpanel.add(busistatus);
			rightpanel.add(ccode);
			rightpanel.add(receiver);
			rightpanel.add(receiveddr);
			
			rightpanel.add(receivezip);
			rightpanel.add(receivephone);
			rightpanel.add(mark,new FormData(161, 46));
			
//			rightpanel.add(bcode);
			
			//_________________________________
			
			
			TableData td = new TableData();
			td.setColspan(1);
			td.setRowspan(1);
			
			TableData td2 = new TableData();
			td2.setColspan(2);
			td2.setRowspan(1);
			// 对齐方式
			td.setHorizontalAlign(HorizontalAlignment.LEFT);
			td.setVerticalAlign(VerticalAlignment.TOP);
			leftpanel.inited();
			rightpanel.inited();
			FieldSet fieldSet = new FieldSet();
			fieldSet.setHeading("发货单基本信息");
			fieldSet.setLayout(new TableLayout(2));
			fieldSet.add(leftpanel,td);
			fieldSet.add(rightpanel,td);
			
			fieldSet.add(CreateGCodePanel(),td2);
			 final BorderLayout layout = new BorderLayout();  
			 panel.setLayout(layout);  
			 BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);  
			    centerData.setMargins(new Margins(5, 0, 5, 0));  
			    BorderLayoutData southData = new BorderLayoutData(LayoutRegion.SOUTH, 130);  
			    southData.setSplit(true);  
			    southData.setCollapsible(true);  
			    
			    southData.setFloatable(true);  
			    southData.setMargins(new Margins(0, 5, 5, 5));  
			 
			panel.add(fieldSet,centerData);
//			panel.add(SystemInfo(),southData);
			
			
			busistatus.addListener(Events.Change,getListener() );
			return panel;
		}
		private ContentPanel SystemInfo()
		{
			 ContentPanel noth = new ContentPanel();
			 BaseFormPanel leftpanel = new BaseFormPanel(getStore());
				leftpanel.setBodyBorder(false);
				leftpanel.setHeaderVisible(false);
				
				BaseFormPanel rightpanel = new BaseFormPanel(getStore());
				rightpanel.setBodyBorder(false);
				rightpanel.setHeaderVisible(false);
				
				
				//-----------------
				TextField<String> vprepare = new TextField<String>();
				vprepare.setName("vprepare");
				vprepare.setEnabled(false);
				vprepare.setFieldLabel("制单人");
				TextField<String> predate = new TextField<String>();
				predate.setName("vprepare");
				predate.setEnabled(false);
				predate.setFieldLabel("制单日期");
				TextField<String> modifydate = new TextField<String>();
				modifydate.setName("modifydate");
				modifydate.setEnabled(false);
				modifydate.setFieldLabel("最近修改日期");
				
				TextField<String> odate = new TextField<String>();
				odate.setName("odate");
				odate.setEnabled(false);
				odate.setFieldLabel("提交审批日期");
	
				
				//-----------------
				leftpanel.add(vprepare);
				rightpanel.add(predate);
					leftpanel.add(modifydate);
					rightpanel.add(odate);
				
				TableData td = new TableData();
				td.setColspan(1);
				td.setRowspan(1);
				// 对齐方式
				td.setHorizontalAlign(HorizontalAlignment.LEFT);
				td.setVerticalAlign(VerticalAlignment.TOP);
				leftpanel.inited();
				rightpanel.inited();
				FieldSet fieldSet = new FieldSet();
			//fieldSet.setHeading("单据信息");
				fieldSet.setLayout(new TableLayout(2));
				fieldSet.add(leftpanel,td);
				fieldSet.add(rightpanel,td);
				noth.setHeight("400px");
				noth.add(fieldSet);
				noth.setHeading("单据信息");
//				noth.setExpanded(false);
				//noth.collapse();
			    return noth;
		}
		
		
		/**
		 * 商品
		 * @return
		 */
		private ContentPanel CreateGCodePanel() {

			CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
			List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
			columns.add(cbs.getColumn());
			
//			ColumnConfig codename = new ColumnConfig("codename", "商品2", 100);
//			TextField<String> codenametext = new TextField<String>();
//			codename.setEditor(new CellEditor(codenametext));
//			columns.add(codename);
			ColumnConfig cgicode = new ColumnConfig("cgicode", "编码", 100);
			TextField<String> cgicodetext = new TextField<String>();
			cgicode.setEditor(new CellEditor(cgicodetext));
			columns.add(cgicode);
			
			ColumnConfig cgcode = new ColumnConfig("cgcode", "商品", 100);
			
			columns.add(cgcode);
			ColumnConfig modeltype = new ColumnConfig("modeltype", "规格", 100);
			columns.add(modeltype);
			ColumnConfig qty = new ColumnConfig("qty", "数量", 120);
			
			NumberField qtytext = new NumberField();
			qty.setEditor(new CellEditor(qtytext));
			columns.add(qty);
			ColumnConfig upric = new ColumnConfig("upric", "单价", 100);
			NumberField uprictext = new NumberField();
			upric.setEditor(new CellEditor(uprictext));
			columns.add(upric);
			ColumnConfig qtyunit = new ColumnConfig("qtyunit", "单位", 100);
			TextField<String> qtyunittext = new TextField<String>();
			qtyunit.setEditor(new CellEditor(qtyunittext));
			columns.add(qtyunit);
	


			ModelType type = new ModelType();
			type.setRoot("records");
			type.setRecordName("record");

			type.addField("idx");
			type.addField("codename");
			type.addField("cgicode");
			type.addField("cgcode");

			
			type.addField("gcode");
			type.addField("qty");
			type.getField("qty").setType(Double.class);
			type.addField("qtyunit");
			type.addField("upric");
			type.getField("upric").setType(Double.class);
			type.addField("modeltype");
			type.addField("upscode");
			type.addField("originalicode");
			
			type.addField("buyprice");
			type.getField("buyprice").setType(Double.class);
			type.addField("saleprice");
			type.getField("saleprice").setType(Double.class);
			
			type.addField("cgcode");
			type.addField("modeltype");
			StoreInfo info = new StoreInfo();

			info.setTablename("shiporderg");
			info.setSql("select * from shiporderg where codename='{codename}' and upicode={icode}");
			info.setParent(getStore());// 关联主表
			//info.setAutoinccolumn("idx"); // 自增字段，如果子表一定需要
			info.setLinkparentcolumns(new String[] { "codename","icode" }); // 关联主表字段
			info.setLinkparent_chile_columns(new String[]{"codename","upicode"});
			info.setKeyname(new String[] {  "icode" }); // 主键
			 shipordergcode = new BaseStore<BusiObject>(type, info);
			//contractgcode.setName("shiporderg");
			//contractgcode.setKeyname(new String[] { "codename", "idx" }); // 主键
			ColumnModel cm = new ColumnModel(columns);
			BaseGrid<BusiObject> contractgcodegrid = new BaseGrid<BusiObject>(shipordergcode, cm);

			cbs.setSelectionMode(SelectionMode.SINGLE);

			contractgcodegrid.setSelectionModel(cbs);
		
			contractgcodegrid.setSize(583	, 152);
			
			registerStore(shipordergcode);
			
			ToolBar tb = new ToolBar();
			addstorelistg.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.outstore()));
			
			addstorelistg.addListener(Events.Select, getListener());
			tb.add(addstorelistg);
			tb.add(gcodetip);
			ContentPanel panel = new ContentPanel();
			panel.setTopComponent(tb);
			panel.setHeaderVisible(false);
			panel.add(contractgcodegrid);
			panel.setAutoHeight(true);
			return panel;
		}
	/**
	 * @return the store
	 */
	public BaseStore<BusiObject> getStore() {
		return store;
	}

	/**
	 * @param store the store to set
	 */
	public void setStore(BaseStore<BusiObject> store) {
		this.store = store;
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                      
				try {                                                        
					if (sync == 1) {                                           
						if (be.getType() == Events.Select) {                     
							if (be.getSource().equals(addstorelistg)) {   
//								 if(scode.getValue()==null)
//								 {
//									 Window.alert("请先选择“仓库”");
//									 return;
//								 }
								 GcodeSelectDialog gd = new GcodeSelectDialog(){
										public  void doposted(List<BusiObject> at) {
											
											for(BusiObject bo:at)
											{
												HashMap<String,Object> h = new HashMap<String,Object>();
												h.put("cgicode", bo.get("cgicode"));
												h.put("cgcode", bo.get("cgcode"));
												h.put("gcode", bo.get("gcode"));
												h.put("modeltype", bo.get("modeltype"));
												h.put("qty", bo.get("lastqty"));
												h.put("qtyunit", bo.get("qtyunit"));
												h.put("upscode", bo.get("scode"));
												h.put("originalicode", bo.get("upicode"));
												h.put("upric", bo.get("saleprice"));
												h.put("buyprice", bo.get("buyprice"));
												h.put("saleprice", bo.get("saleprice"));
												shipordergcode.add(h);
											//	gcodetip.setHtml("默认是该商品库存余额，请修改“数量”吧");
												
											//	gcodetip.el().blink(FxConfig.NONE);  
											}
											this.close();
										}
								 };
								 
								
								
//								 gd.setScode(scode.getValue());
//								 GWT.log(scode.getValueCode()+" v "+ scode.getValue().get("code"),null);
								 gd.show();
								 
                                                                     
							}       
							
						}
						else if (be.getType() == Events.Hide) {    
							
						}
					
						else if(be.getType() == Events.Change)
						{
							if(be.getSource().equals(busistatus))
							{
								GWT.log("busistatus="+busistatus.getValue());
							}
							else if(be.getSource().equals(ccode))
							{
								
							}
						}
						else if (be.getType() == Events.KeyUp) {               
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{                                                    
								}                                                    
							}                                                      
						}                                                        
					}                                                          
				} finally {                                                  
					sync--;                                                    
				}                                                            
			}

		                                                       
                                                                     
		};                                                               
		return defaultlistener;                                          
	}
	protected void ratify()
	{
	
		
		if(BeforeRatify())
		{
			if(OnRatify())
			{
				AfterRatify();
			}
		}
	}
	@Override
	public boolean AfterRatify() {
		// 
		return true;
	}
	@Override
	public boolean BeforeRatify() {

		return true;
	}
	@Override
	public boolean OnRatify() {

		this.mask("提交....");
		int index = store.getCurcowindex();
		String icode = store.getValue(index, "icode").toString();
		//store._trySave(index);
		String sql = "update shiporder set busistatus='131072' where icode ='"
				+ icode + "' ";
		CommandSyncContainer list = new CommandSyncContainer();
		CommandSyncsql commandsql = new CommandSyncsql();
		CommandPrepareCall commandpc = new CommandPrepareCall();
		
		commandsql.getV().addAll(store._trySave(index));
		commandsql.getV().add(sql);
		commandsql.setContinueorrollback(false);
		
		commandpc.setCallname("ShipOrderList (?)");
		commandpc.addItem(icode, CommandPrepareCall.STRING);
		commandpc.setContinueorrollback(false);
		

		list.add(commandsql);
		list.add(commandpc);
		
//		CommandSyncCopyUP cu = new CommandSyncCopyUP();
//		cu.setIcode(icode);
//		
//		list.add(cu);

		final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.SendCommandSync(list,
				this);
		
	
		
		//store.trySave(index);
		return true;
	
	}
	@Override
	public void onFailure(Throwable caught) {
		MessageBox.alert("错误", "网络出现连接失败！请重新提交。"+caught.getMessage(), null);
		this.unmask();// 提交的时候mask，现在取消mask
		
	}
	@Override
	public void onSuccess(CommandSyncReturnObject cyro) {
		if(cyro.isB())
		{
			store.setValue("busistatus", "131072");
			store.commitChanges();
			Info.display("", "提交成功");
		
		}
		else
		{
			MessageBox.alert("错误", cyro.getMessage(), null);
		}
		this.unmask();// 提交的时候mask，现在取消mask
		
	}   	
	
}
